<template>
  <div>
    <el-dialog
      :title="title"
      :close-on-click-modal="false"
      :visible.sync="visible"
      width="700px"
    >
      <el-form
        :model="classForm"
        :rules="classFormRules"
        ref="classForm"
        label-width="100px"
      >
        <div v-if="mode === 'add'">
          <el-row :gutter="20">
            <el-col :span="10">
              <el-form-item label="年级" prop="initGrade">
                <nice-select
                  v-model="classForm.initGrade"
                  placeholder="请选择年级"
                  clearable
                  :options="selectEnums.grade"
                  labelkey="name"
                  valuekey="id"
                ></nice-select>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="班级数量" prop="count">
                <!-- <nice-select
              v-model="classForm.count"
              placeholder="请选择班级数量"
              clearable
              :options="classNumList"
              
            ></nice-select> -->
                <el-input
                  placeholder="请输入班级数量"
                  v-model="classForm.count"
                  type="text"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-button type="primary" @click="changeClassNum"
                >生成班级</el-button
              >
            </el-col>
          </el-row>

          <div v-for="(item, index) in classForm.classList" :key="index">
            <el-form-item
              label="班级名称"
              :prop="'classList.' + index + '.name'"
            >
              <el-input
                v-model="item.className"
                placeholder="请输入班级名称"
              ></el-input>
            </el-form-item>
          </div>
        </div>
        <div v-if="mode === 'edit'">
          <el-row :gutter="20">
            <el-col :span="20">
              <el-form-item label="年级" prop="initGrade">
                <nice-select
                  v-model="classForm.grade"
                  placeholder="请选择年级"
                  clearable
                  :options="selectEnums.grade"
                  @change="changeGrade"
                  labelkey="name"
                  valuekey="id"
                ></nice-select>
              </el-form-item>
            </el-col>
          </el-row>

          <div v-for="(item, index) in classForm.classList" :key="index">
            <el-form-item
              label="班级名称"
              :prop="'classList.' + index + '.name'"
            >
              <el-input
                v-model="item.className"
                placeholder="请输入班级名称"
              ></el-input>
            </el-form-item>
          </div>
        </div>
        <!-- <el-row :gutter="20" v-else>
          <el-col :span="12">
            <el-form-item label="年级" prop="grade">
              <nice-select
                v-model="classForm.grade"
                placeholder="请选择年级"
                clearable
                :options="gradeList"
                @change="changeGrade"
              ></nice-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="班级名称：" prop="class">
              <nice-select
                v-model="classForm.class"
                placeholder="请选择班级"
                clearable
                :options="classList"
              ></nice-select>
            </el-form-item>
          </el-col>
        </el-row> -->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false" size="small">取消</el-button>
        <el-button
          type="primary"
          @click="dataFormSubmit"
          size="small"
          v-preventReClick
          >确定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { tableDeleted, cascadeQuery } from '@/api/api'
import { addSchoolClass } from '@/api/user'
import {
  adminschoolclassesadd,
  adminschoolclassesgradeClassesStatistics,
  schoolclassesupdateBatch
} from '@/api/lcmapi.js'

export default {
  data () {
    return {
      visible: false,
      title: '',
      classForm: {
        grade: '',
        class: '',
        count: '',
        classList: []
      },
      classList: [],
      classNum: '',
      classNumList: [
        1,
        2,
        3,
        4,
        5,
        6,
        7,
        8,
        9,
        10,
        11,
        12,
        13,
        14,
        15,
        16,
        17,
        18,
        19,
        20
      ],
      classFormRules: {
        grade: [{ required: true, message: '请选择年级', trigger: 'change' }],
        class: [{ required: true, message: '请选择班级', trigger: 'change' }],
        count: [{ required: true, message: '请输入班级个数', trigger: 'blur' }]
      }
    }
  },
  props: {
    mode: '',
    schoolId: '',
    selectEnums: {
      type: Object,
      default: function () {
        return {}
      }
    },
    gradeList: {
      type: Array,
      default: function () {
        return []
      }
    }
  },
  methods: {
    init (id) {
      this.visible = true
      this.classNumList = []
      for (let i = 1; i <= 20; i++) {
        this.classNumList.push({ label: i, value: i })
      }
      this.title =
        this.mode === 'add'
          ? '新增班级'
          : this.mode === 'edit'
          ? '编辑班级'
          : '删除班级'
      this.$nextTick(() => {
        this.$refs['classForm'].resetFields()
        this.classForm.classList = []
      })
    },
    // async changeGrade() {
    //   this.classForm.classList = [];
    //   this.classForm.count = "";
    //   let res = await cascadeQuery({
    //     table_name: "nice_school_classes",
    //     condition: {
    //       school_id: this.schoolId,
    //       init_grade: this.classForm.grade,
    //     },
    //   });
    //   if (res[0]) {
    //     return;
    //   }
    //   if (res[1] && res[1].code === 0) {
    //     this.classList = res[1].data.map((ele) => {
    //       return {
    //         label: ele.class_name,
    //         value: ele.id,
    //       };
    //     });
    //   } else {
    //     this.$message.error(res[1].msg);
    //   }
    // },
    // 表单提交
    dataFormSubmit () {
      this.$refs['classForm'].validate(valid => {
        if (valid) {
          this.submit(this.classForm)
        }
      })
    },
    async changeGrade () {
      let res = await adminschoolclassesgradeClassesStatistics({
        schoolId: this.schoolId,
        grade: this.classForm.grade,
        classType: "normal"
      })
      if (res[0]) {
        return
      }
      if (res[1] && res[1].code === 0) {
        this.classForm.classList = []
        let classList = []
        res[1].data.forEach(item => {
          classList.push({
            id: item.id,
            className: item.className,
            schoolId: this.schoolId,
            initGrade: this.classForm.grade
          })
        })
        this.classForm.classList = classList
        console.log(this.classForm.classList)
      } else {
        this.$message.error(res[1].msg)
      }
    },
    changeClassNum (e) {
      this.$refs.classForm.clearValidate()
      this.classForm.classList = []
      let classLength = this.classList.length
      if (!this.classForm.count) {
        this.$message.error('请输入生成班级的数量')
        return
      }
      if (!this.classForm.initGrade) {
        this.$message.error('请选择要生成的班级')
        return
      }

      let _arr = this.selectEnums.grade.filter(
        item => item.id == this.classForm.initGrade
      )
      console.log(_arr, this.selectEnums.grade)
      for (let i = 1; i < Number(this.classForm.count) + 1; i++) {
        this.classForm.classList.push({
          className: `${_arr[0].name.length==3?_arr[0].name.substr(0, 1):_arr[0].name}（${classLength + i}）班`,
          schoolId: this.schoolId,
          initGrade: this.classForm.initGrade
        })
      }
    },
    async submit (e) {
      let res =
        this.mode === 'add'
          ? await adminschoolclassesadd({
            classesList: this.classForm.classList
          })
          : this.mode === 'edit'
          ? await schoolclassesupdateBatch({
            classesList: this.classForm.classList
          })
          : await tableDeleted({ ...this.classForm, schoolId: this.schoolId })
      if (res[0]) {
        return
      }
      let data = res[1]

      if (data && data.code === 0) {
        this.$message({
          message:
            this.mode === 'add'
              ? '新增班级成功！'
              : this.mode === 'edit'
              ? '编辑班级成功！'
              : '删除班级成功',
          type: 'success',
          duration: 1500,
          onClose: () => {
            this.visible = false
            this.$emit('refreshDataList')
          }
        })
        this.classForm = {
          grade: '',
          class: '',
          count: '',
          classList: []
        }
      } else {
        this.$message.error(data.msg)
      }
    }
  }
}
</script>
